<?php
/**
 * Created by PhpStorm.
 * User: nightelf
 * Date: 2020/1/15
 * Time: 16:15
 */

namespace App\Http\Model;


use Illuminate\Support\Facades\DB;

class ProjectBudgetModel
{
    const TABLE = 'project_budget';
    /**
     * @param array $data
     * @return array
     */
    public function info(array $data)
    {
        $result = DB::table(self::TABLE)->where($data)->first();
        return empty($result) ? [] : get_object_vars($result);
    }

    /**
     * @param array $data
     * @return mixed
     */
    public function getSum(array $data)
    {
        return DB::table(self::TABLE)
            ->where(function($query) use($data){
                if (!empty($data['areaId'])){
                    $query->where(self::TABLE.'.areaId',$data['areaId']);
                }
                if (!empty($data['sectionId'])){
                    $query->where(self::TABLE.'.sectionId',$data['sectionId']);
                }
                if (!empty($data['professionId'])){
                    $query->where(self::TABLE.'.professionId',$data['professionId']);
                }
            })
            ->select(DB::raw('sum('.self::TABLE.'.totalPrice) as totalPrice'))
            ->value('totalPrice');
    }

    /**
     * @param array $data
     * @return mixed
     */
    public function budgetLists(array $data)
    {
        return DB::table(self::TABLE)
            ->leftJoin('project_section','project_section.id','=',self::TABLE.'.sectionId')
            ->where(function ($query) use ($data){
                if (!empty($data['professionId'])){
                    $query->where(self::TABLE.'.professionId', $data['professionId']);
                }
                if (!empty($data['sectionId'])){
                    $query->where(self::TABLE.'.sectionId', $data['sectionId']);
                }
            })
            ->select(self::TABLE.'.price',self::TABLE.'.id as budgetId','project_section.area','project_section.formworkArea')
            ->get()->toArray();
    }

    /**
     * @param array $param
     * @return bool
     */
    public function editBudget(array $param)
    {
        foreach ($param['data'] as  $d){
            $insertData = [
                'projectId'=>$param['projectId'],
                'areaId'=>$param['areaId'],
                'sectionId'=>$param['sectionId'],
                'professionId'=>$d['professionId'],
//                'amount'=>$d['amount'],
                'price'=>$d['price'],
                'totalPrice'=>$d['totalPrice'],
                'adminId'=>$param['adminId'],
            ];
            if (empty($d['id'])){
                DB::table(self::TABLE)->insert($insertData);
            }else{
                DB::table(self::TABLE)->where('id',$d['id'])->update($insertData);
            }
        }
        return true;
    }


}